<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                        v-model="form"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       :upload-error="uploadError"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                       <template slot="menuLeft">
                            <el-button
                            icon="el-icon-circle-plus"
                            size="small"
                            v-if="addBtn"
                            type="primary"
                            @click="addNodeForm">新增</el-button>
                            <el-button
                            size="small"
                            v-if="addBtn"
                            @click="copyDialog">复制</el-button>
                        </template>
                        <template slot="dishesNameForm" slot-scope="scope">
                            <!-- <label for="dishesNameForm" class="red-star" slot="label">菜品名称</label> -->
                            <el-input :disabled="validEdit" @click.native="choseDinner" :style="{'pointer-events': validEdit ? 'none': ''}" v-model="namestr"></el-input>
                        </template>
                        <template slot="menu" slot-scope="scope">
                            <el-button type="text"
                            icon="el-icon-circle-view"
                            size="small"
                            v-if="editBtn"
                            @click="viewNodeForm(scope.row,scope.index)">编辑</el-button>
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog
            :visible.sync="modal"
            v-if="modal"
            title="选菜"
            width="1200px"
            @close="closeDialog"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body>
            <avue-crud ref="crud1"
                :page.sync="page1"
                :data="tableData1"
                :table-loading="tableLoading1"
                :option="tableOption1"
                :upload-error="uploadError"
                @selection-change="selectionChange"
                @on-load="getList1"
                @search-change="searchChange1"
                @refresh-change="refreshChange1"
                @size-change="sizeChange1"
                @current-change="currentChange1">
            </avue-crud>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="alarmHandle">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :visible.sync="modal1"
            v-if="modal1"
            title="复制菜谱"
            width="800px"
            class="copy-dialog"
            @close="closeDialog1"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body>
            <el-form ref="form1" :model="form1" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="菜品类别" prop="categoryId">
                            <el-select v-model="form1.categoryId"
                                        placeholder="请选择菜品类别"
                                        clearable>
                                <el-option v-for="item in optionsLb"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.categoryId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="时段" prop="periods">
                            <el-select v-model="form1.periods"
                                        multiple
                                        placeholder="请选择时段"
                                        clearable>
                                <el-option v-for="item in optionsSd"
                                        :key="item.id"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="复制方式" prop="method">
                            <el-radio-group v-model="form1.method" @change="changeMethod">
                                <el-radio :label="'1'">一日菜单复制为多日菜单</el-radio>
                                <el-radio :label="'2'">源日期范围复制目标对应日期范围</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="源菜谱日期" prop="dateRange">
                             <el-date-picker
                                 @change="changeDate"
                                v-model="form1.dateRange"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="目标菜谱日期" prop="dateRange1">
                            <el-date-picker
                                @change="changeDate1"
                                v-model="form1.dateRange1"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog1">取 消</el-button>
                <el-button type="primary" @click="alarmHandle1('form1')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {fetchList, addObj, putObj, delObj, copyObj} from '@/api/dining/diningmenu'
    import {fetchList as fetchList1} from '@/api/dining/diningdishes'
    import {fetchList as fetchList2} from '@/api/dining/diningdishescategory'
    import { remote } from "@/api/admin/dict";
    import {getDiffDates} from '@/util/date'
    import {tableOption} from '@/const/crud/dining/diningmenu'
    import {mapGetters} from 'vuex'

    export default {
        name: 'diningmenu',
        data() {
            return {
                form: {},
                form1: {
                    dateRange: '',
                    dateRange1: '',
                    categoryId: '',
                    periods: [],
                    method: ''
                },
                optionsLb: [],
                optionsSd: [],
                searchForm: {},
                tableData: [],
                modal: false,
                modal1: false,
                namestr: '',
                validEdit: false,
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                dishList: [],
                choseList: [],
                tableLoading: false,
                tableOption: tableOption,
                searchForm1: {},
                tableData1: [],
                page1: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                rules: {
                    categoryId: [
                        { required: true, message: '请选择菜品分类', trigger: 'change' }
                    ],
                    periods: [
                        { required: true, message: '请选择时段', trigger: 'change' }
                    ],
                    method: [
                        { required: true, message: '请选择复制方式', trigger: 'change' }
                    ],
                    dateRange: [
                        { required: true, message: '请选择源菜谱日期', trigger: 'change' }
                    ],
                    dateRange1: [
                        { required: true, message: '请选择目标菜谱日期', trigger: 'change' }

                    ]
                },
                tableLoading1: false,
                tableOption1: {
                    "border": true,
                    "index": true,
                    selection: true,
                    // reserveSelection:true,
                    "indexLabel": "序号",
                    "stripe": true,
                    "menuAlign": "center",
                    menu: false,
                    addBtn: false,
                    "align": "center",
                    "dialogClickModal": false,
                    "searchMenuSpan": 6,
                    "column": [
                    {
                    "type": "input",
                    "label": "名称",
                    "prop": "dishesName",
                    "span": 12,
                    search: true,
                    maxlength: 24,
                    rules: [{
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    }],
                    },	  {
                    "type": "select",
                    "label": "菜品类别",
                    "prop": "categoryId",
                    "span": 12,
                    search: true,
                    rules: [{
                        required: true,
                        message: '请选择菜品类别',
                    }],
                    dicUrl: '/act/diningdishescategory/page?size=-1&status=1',
                    props: {
                        label: 'name',
                        value: 'categoryId',
                        res: "data.records"
                    },
                    },	  {
                    "type": "number",
                    "label": "早餐价格",
                    "prop": "morningPrice",
                    "span": 12,
                    maxRows: 1000000,
                    },	  {
                    "type": "number",
                    "label": "午餐价格",
                    "prop": "noonPrice",
                    "span": 12,
                    maxRows: 1000000,
                    },	  {
                    "type": "number",
                    "label": "晚餐价格",
                    "prop": "nightPrice",
                    "span": 12,
                    maxRows: 1000000
                    },	  {
                        "label": "封面",
                        "prop": "cover",
                        type: 'upload',
                        width: 140,
                        loadText: '附件上传中，请稍等',
                        listType:'picture-img',
                        accept: ["image/png","image/jpeg","image/jpg"],
                        tip: '只能上传jpg，png图片不超过20MB',
                        fileSize: 20480,
                        propsHttp: {
                            res: 'data'
                        },
                        canvasOption: {
                            text: ' ',
                            ratio: 0.1
                        },
                        action: "/act/file/upload"
                    }  ]
                }
            }
        },
        watch: {
            'form.period':{
                handler(val){
                    let list = this.dishList.filter(item => {
                        return item.dishesId === this.form.dishesId
                    })
                    if (list.length) {
                        if (this.form.period === '1') {
                            this.form.price = list[0].morningPrice
                        } else if(this.form.period === '2') {
                            this.form.price = list[0].noonPrice
                        } else if(this.form.period === '3') {
                            this.form.price = list[0].nightPrice
                        }
                    }
                }
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: this.vaildData(this.permissions.act_diningmenu_del, false),
                    editBtn: false
                };
            },
            addBtn() {
                return this.permissions.act_diningmenu_add
            },
            editBtn() {
                return this.permissions.act_diningmenu_edit
            }
        },
        created() {
             fetchList1({
                size: -1,
                status: '1'
            }).then(response => {
                this.dishList = response.data.data.records
            })
            remote('dishes_period_status').then(response => {
                this.optionsSd = response.data.data
            })
            fetchList2({size: -1, status: '1'}).then(response => {
                this.optionsLb = response.data.data.records
            })
        },
        methods: {
            uploadError(file, done) {
                this.$message.error('只能上传jpg，png图片不超过20MB')
            },
            openDialogform() {
                this.modal = true
            },
            addNodeForm(row, index) {
                this.namestr = ''
                this.validEdit = false
                this.$refs.crud.rowAdd(row, index)
            },
            changeMethod(value) {
                if (value === '1' && this.form1.dateRange.length > 1 && this.form1.dateRange[0] !== this.form1.dateRange[1]) {
                    this.$message.error('源菜谱日期请选择同一日')
                    this.form1.dateRange = ''
                    return
                }
                if (value === '2' && this.form1.dateRange.length > 1 && this.form1.dateRange1.length > 1) {
                    let num = getDiffDates(this.form1.dateRange[0], this.form1.dateRange[1])
                    let num1 = getDiffDates(this.form1.dateRange1[0], this.form1.dateRange1[1])
                    if (num !== num1) {
                         this.$message.error('源菜谱日期与目标菜谱日期间隔需一致')
                        this.form1.dateRange1 = ''
                        return
                    }
                }
            },
            changeDate(value) {
                if (value.length > 1) {
                    let num = getDiffDates(value[0], value[1])
                    if (num > 31) {
                        this.$message.error('日期间隔请不要超过31天')
                        this.form1.dateRange = ''
                        return
                    }
                    if (this.form1.method === '1' && value[0] !== value[1]) {
                        this.$message.error('源菜谱日期请选择同一日')
                        this.form1.dateRange = ''
                        return
                    }
                    if (this.form1.method === '2' && value.length > 1 && this.form1.dateRange1.length > 1) {
                        let num = getDiffDates(value[0], value[1])
                        let num1 = getDiffDates(this.form1.dateRange1[0], this.form1.dateRange1[1])
                        if (num !== num1) {
                            this.$message.error('源菜谱日期与目标菜谱日期间隔需一致')
                            this.form1.dateRange1 = ''
                            return
                        }
                    }
                }
            },
            changeDate1(value) {
                if (value.length > 1) {
                    let num = getDiffDates(value[0], value[1])
                    if (num > 31) {
                        this.$message.error('日期间隔请不要超过31天')
                        this.form1.dateRange = ''
                        return
                    }
                }
                if (this.form1.method === '2' && value.length > 1 && this.form1.dateRange.length > 1) {
                    let num = getDiffDates(value[0], value[1])
                    let num1 = getDiffDates(this.form1.dateRange[0], this.form1.dateRange[1])
                    if (num !== num1) {
                        this.$message.error('源菜谱日期与目标菜谱日期间隔需一致')
                        this.form1.dateRange1 = ''
                        return
                    }
                }
            },
            copyDialog() {
                this.modal1 = true
            },
            viewNodeForm(row, index) {
                this.namestr = row.dishesName
                this.validEdit = true
                this.$refs.crud.rowEdit(row, index)
            },
            selectionChange(list){
                this.choseList = list
            },
            choseDinner() {
                this.modal = true
            },
            getList(page, params) {
                this.tableLoading = true
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            alarmHandle() {
                let nameList = this.choseList.map(item => {
                    return item.dishesName
                })
                this.namestr = nameList.join()
                this.form.dishesName = nameList.join()
                this.modal = false
            },
            closeDialog() {
                this.searchForm1 = {}
                this.choseList = []
                this.modal = false
            },
            alarmHandle1(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.form1.startDate = this.form1.dateRange[0]
                        this.form1.endDate = this.form1.dateRange[1]
                        this.form1.targetEndDate = this.form1.dateRange1[1]
                        this.form1.targetStartDate = this.form1.dateRange1[0]
                        copyObj(this.form1).then(response => {
                            this.$message.success('复制成功')
                            this.form1 = {
                                dateRange: '',
                                dateRange1: '',
                                categoryId: '',
                                periods: [],
                                method: ''
                            }
                            this.modal1 = false
                            this.getList(this.page)
                        })
                    }
                })
            },
            closeDialog1() {
                this.form1 = {
                    dateRange: '',
                    dateRange1: '',
                    categoryId: '',
                    periods: [],
                    method: ''
                }
                this.modal1 = false
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.menuId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                if (this.choseList.length > 0) {
                    row.dishesIds = this.choseList.map(item => {
                        return item.dishesId
                    })
                } else {
                    this.$message.error('请选择菜品')
                    loading();
                    return
                }
                let params = {
                    dishesIds: row.dishesIds,
                    status: row.status,
                    menuDate: row.menuDate,
                    period: row.period
                }
                addObj(params).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.choseList = []
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            },

            getList1(page, params) {
                this.tableLoading1 = true
                fetchList1(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize,
                    status: '1'
                }, params, this.searchForm1 )).then(response => {
                    this.tableData1 = response.data.data.records
                    this.page1.total = response.data.data.total
                    this.tableLoading1 = false
                }).catch(() => {
                    this.tableLoading1=false
                })
            },
            sizeChange1(pageSize){
                this.page1.pageSize = pageSize
            },
            currentChange1(current){
                this.page1.currentPage = current
            },
            searchChange1(form, done) {
                this.searchForm1 = form
                this.page1.currentPage = 1
                this.getList1(this.page1, form)
                done()
            },
            refreshChange1() {
                this.getList1(this.page1)
            }
        }
    }
</script>
<style scoped lang="scss">
.copy-dialog{
    /deep/.el-date-editor, .el-select {
        width: 100%;
    }
}
</style>